﻿using System.Drawing.Drawing2D;

namespace LightCAD.Model
{
    public class Solid3dAction
    {
        protected DocumentRuntime docRt;
        protected IDocumentEditor docEditor;
        protected CommandCenter commandCenter;
        protected ICommandControl commandCtrl;
        protected Model3DEditRuntime model3dRuntime;
        protected Snap3dRuntime snap3dRuntime;
        protected Solid3dAction(IDocumentEditor docEditor)
        {
            this.docEditor = docEditor;
            this.docRt = docEditor.DocRt;
            this.commandCenter = this.docEditor.CommandCenter;
            this.commandCtrl = this.commandCenter.Commander;
            this.model3dRuntime = docEditor as Model3DEditRuntime;
            this.snap3dRuntime = this.model3dRuntime.Snap3DRuntime;
        }
        public virtual List<Object3D> Render(LcSolid3d solid, Matrix4 matrix = null)
        {
            solid.Solid.Mesh();
            var geoData = solid.Solid.Geometry;
            var geo = new BufferGeometry();
            geo.setAttribute("position", new BufferAttribute(geoData.Verteics, 3, false));
            geo.setIndex(new BufferAttribute(geoData.Indics, 1));
            geo.groups.AddRange(geoData.Groups);
            geo.applyMatrix4(solid.Matrix);
            if (matrix != null)
                geo.applyMatrix4(matrix);
            geo.computeVertexNormals();

            var materials = solid.Materials.Select(m => new MeshPhongMaterial() { color = m.Color, opacity = m.Opcity, transparent = m.Opcity < 1 });
            var mesh = new Mesh(geo, materials.ToArray());

            var lineGeoData = solid.Solid.Edge;
            var lineGeo = new BufferGeometry();
            lineGeo.setAttribute("position", new BufferAttribute(lineGeoData.Verteics, 3, false));
            lineGeo.setIndex(new BufferAttribute(lineGeoData.Indics, 1));
            lineGeo.applyMatrix4(solid.Matrix);
            if (matrix != null)
                lineGeo.applyMatrix4(matrix);
            var line = new LineSegments(lineGeo, new LineBasicMaterial { color = new Color(0x00000000) });
            return new List<Object3D> { mesh, line };
        }

        public void StartAction()
        {
            this.docEditor.CommandCenter.InAction = true;
        }
        public void EndAction()
        {
            this.commandCtrl.Prompt(string.Empty);

            this.commandCtrl.SetCurMethod(null);
            this.commandCtrl.SetCurStep(null);
            this.docEditor.CommandCenter.InAction = false;
        }
    }
}
  
